package com.bondqin.sakila.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bondqin.sakila.domain.ActorInfoDo;
import com.bondqin.sakila.domain.CustomerListDo;
import com.bondqin.sakila.domain.SalesByFilmCategoryDo;
import com.bondqin.sakila.domain.SalesByStoreDo;
import com.bondqin.sakila.entity.ActorInfo;
import com.bondqin.sakila.entity.Category;
import com.bondqin.sakila.entity.City;
import com.bondqin.sakila.entity.CustomerList;
import com.bondqin.sakila.entity.Staff;
import com.bondqin.sakila.entity.Store;
import com.bondqin.sakila.repository.ActorInfoDao;
import com.bondqin.sakila.repository.CategoryDao;
import com.bondqin.sakila.repository.CustomerListDao;
import com.bondqin.sakila.repository.StoreDao;
import com.bondqin.sakila.service.CommonService;
import com.bondqin.sakila.util.ConvertUtil;

@Service
public class CommonServiceImpl implements CommonService {
	@Autowired
	private StoreDao storeDao;
	
	@Autowired
	private CategoryDao categoryDao;
	
	@Autowired
	private ActorInfoDao actorInfoDao;
	
	@Autowired
	private CustomerListDao customerListDao;

	@Override
	public SalesByStoreDo querySalesByStore(Integer storeId) {
		Store source = storeDao.findOne(storeId);
		
		SalesByStoreDo salesDo = new SalesByStoreDo();
		
		StringBuilder store = new StringBuilder();
		// address is not null
		City city = source.getAddress().getCity();
		// city is not null
		store.append(city.getCity());
		store.append(",");
		// country is not null
		store.append(city.getCountry().getCountry());
		salesDo.setStore(store.toString());
		
		Staff staff = source.getStaff();
		// staff is not null
		salesDo.setManager(staff.getFirstName() + " " + staff.getLastName());
		
		Double totalSales = storeDao.queryTotalSales(source.getStoreId());
		salesDo.setTotalSales(totalSales);

		return salesDo;
	}

	@Override
	public SalesByFilmCategoryDo querySalesByFilmCategory(Integer categoryId) {
		Category source = categoryDao.findOne(categoryId);
		SalesByFilmCategoryDo salesDo = new SalesByFilmCategoryDo();
		
		// category is not null
		salesDo.setCategory(source.getName());
		
		Double totalSales = categoryDao.queryTotalSales(source.getCategoryId());
		salesDo.setTotalSales(totalSales);
				
		return salesDo;
	}

	@Override
	public ActorInfoDo queryActorInfo(Integer actorId) {
		ActorInfo actorInfo = actorInfoDao.findOne(actorId);
		ActorInfoDo actorInfoDo = ConvertUtil.copyConvert(actorInfo, ActorInfoDo.class);
		return actorInfoDo;
	}

	@Override
	public CustomerListDo queryCustomerList(Integer customerId) {
		CustomerList customerList = customerListDao.findOne(customerId);
		CustomerListDo customerListDo = ConvertUtil.copyConvert(customerList, CustomerListDo.class);
		return customerListDo;
	}
}
